package com.lemon.web.util;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.lemon.web.dto.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author lemon
 * @version 1.0
 * @description: TODO
 * @date Create by lemon on 2020-07-06 10:34
 */
@Slf4j
public class ResponseUtil {
    public static Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                         Class selectedConverterType, ServerHttpRequest request,
                                         ServerHttpResponse response, List<String> ignoreUrls) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest servletRequest = attributes.getRequest();
        String requestUri = servletRequest.getRequestURI();

        if (StringUtils.isEmpty(requestUri)) {
            requestUri = request.getURI().getPath();
        }

        if (!ignoreUrls.isEmpty() && ignoreUrls.contains(requestUri.toLowerCase())) {
            log.debug("requestUri ignore:{}", requestUri);
            return body;
        }

        if (!(body instanceof BaseResponse)) {
            BaseResponse baseResponse = new BaseResponse(body);

            // 因为handler处理类的返回类型是String，为了保证数据类型一致性，这里需要将 ResponseResult 转回去
            if (body instanceof String) {
                Gson gson = new Gson();
                return gson.toJson(baseResponse);
            }

            return baseResponse;
        }

        return body;
    }

    /**
     * @param ex
     * @param allErrors
     * @return java.lang.String
     * @description 参数  字段 校验错误信息
     * @author lemon
     * @date 2020-07-02 14:35
     */
    public static String getErrorFieldMessage(Exception ex, List<ObjectError> allErrors) {
        List<String> msgs = Lists.newLinkedList();

        for (ObjectError error : allErrors) {
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                msgs.add(String.format("%s %s", fieldError.getField(), fieldError.getDefaultMessage()));
            } else {
                msgs.add(ex.getMessage());
            }
        }

        return Joiner.on(";").join(msgs);
    }
}
